<template>
  <div>
    <zh-row :gutter="8">
      <zh-col :span="18">
        <div style="height: calc(100vh - 120px);overflow-y: auto;">
          <zh-card>
            <div v-for="item of componentList">
              <component
                  :is="item.mod"
                  v-bind="{ businessKey: props.businessKey,instanceId: String(props.instanceId), taskId: String(item.taskId) }"
                  @getActorListForFunction="getActorListForFunction"
                  :ref="setChildRef(item.mod.name)"
              ></component>
            </div>
          </zh-card>
          <auth-remarks v-if="props.processType === 2 && operationFlag" :hisNodeList="hisNodeList" :hasOperationData="hasOperationData"
              @update:eventType="updateEventType" ref="authRemarksComponent" :otherConfig="otherConfig" :configFromCus="configFromCus"></auth-remarks>
          <auth-remarks v-if="props.processType === 1 && operationFlag" :hasOperationData="hasOperationData"
                        @update:eventType="updateEventType" ref="authRemarksComponent"
                        :otherConfig="{actorWay: 1,actorWayType: 1,examineMode: 2,taskActorConfigForNextStep: otherConfig.taskActorConfigForNextStep}"></auth-remarks>
        </div>
      </zh-col>
      <zh-col :span="6"
      >
        <div style="height: calc(100vh - 120px);overflow-y: auto;">
          <el-steps
              direction="vertical"
              :active="getCompleteProcessStepInfoList.length"
              finish-status="success"
              process-status="finish"
          >
            <el-step v-for="(item, index) of getCompleteProcessStepInfoList">
              <template #title>
                <div class="ant-space-item">
                  <b class="name">{{ item.displayName }}</b>
                </div>
              </template>
              <template #description>
                <div class="ant-space-item" v-if="item.taskType === 0">
                  <b class="name">发起人：{{ item.fullName }} - {{ item.orgName }}</b>
                </div>
                <div v-else>
                  <div class="ant-space-item">
                    <p class="name" v-for="e in getPerformType(item.performType)"
                       :key="e.value">审核方式：{{e.label}}</p>
                    <b class="name">审核人：{{ item.fullName }} - {{ item.orgName }}</b>
                  </div>
                </div>
                <div class="ant-space-item" v-if="item.recordList">
                  <p class="name">转办、委派记录
                    <el-tag v-if="item.taskState === 0"
                        v-for="e in taskTypeFilter(item.taskType)"
                        :key="e.label"
                        :type="e.type"
                        effect="dark"
                    >
                      {{ e.label }}
                    </el-tag>
                  </p>
                  <div v-for="(record,index) in item.recordList" :key="index">{{ record }}</div>
                </div>
                <div class="ant-space-item">
                  <el-tag
                      v-for="e in stateList(item.taskState)"
                      :key="e.label"
                      :type="e.type"
                      effect="dark"
                  >
                    {{ e.label }}
                  </el-tag>
                  <el-tag v-if="item.taskLabel === 0"
                      effect="dark" type="danger"
                  >
                    驳回
                  </el-tag>
                </div>

                <div class="ant-space-item" v-if="item.taskType === 0">
                  发起时间：{{ item.createTime }}
                </div>
                <div class="ant-space-item" v-else>
                  创建时间：{{ item.createTime }}
                </div>
                <div class="ant-space-item" v-if="item.finishTime">
                  完成时间：{{ item.finishTime }}
                </div>
                <div v-if="[1,10,12].indexOf(item.taskType) > -1 && [2,3].indexOf(item.taskState) > -1">
                  <div class="ant-space-item" style="padding-bottom: 5px;">审批意见:</div>
                  <div class="ant-space-item">
                    <span class="ant-space-item">
                      <span class="approval-remark" v-if="item.authYesRemarks"
                      >{{ item.authYesRemarks }}</span
                      >
                      <span class="approval-remark" v-if="item.authNoRemarks"
                      >{{ item.authNoRemarks }}</span
                      >
                    </span>
                  </div>
                </div>
                <div v-if="item.copyPersonTitle" style="margin-top: -20px;">
                  <div class="ant-space-item" style="padding-bottom: 5px;">抄送人:</div>
                  <div class="ant-space-item">
                    <span>{{ item.copyPersonTitle }}</span>
                  </div>
                </div>
                <div v-if="item.taskLabel === 0">
                  <div class="ant-space-item" style="padding-bottom: 5px;">驳回原因:</div>
                  <div class="ant-space-item">
                    <span class="ant-space-item">
                      <span class="approval-remark" v-if="item.rejectReason"
                      >{{ item.rejectReason }}</span
                      >
                    </span>
                  </div>
                </div>
              </template>
            </el-step>
            <el-step v-if="getAuditProcessStepInfoList">
              <template #title>
                <div class="ant-space-item">
                  <b class="name">{{ getAuditProcessStepInfoList.displayName }}</b>
                </div>
              </template>
              <template #description>
                <div v-for="(item, index) of getAuditProcessStepInfoList.list" :key="index">
                  <div class="ant-space-item" v-if="item.taskType === 0">
                    <b class="name">发起人：{{ item.fullName }} - {{ item.orgName }}</b>
                  </div>
                  <div v-else>
                    <div class="ant-space-item" v-if="item.taskState === 0">
                      <p class="name" v-for="e in getPerformType(item.performType)"
                         :key="e.value">审核方式：{{e.label}}</p>
                      <p class="name">审核人：</p>
                      <p class="name">{{ item.currentActorLabel }}</p>
                    </div>
                    <div class="ant-space-item" v-else>
                      <b class="name">审核人：{{ item.fullName }} - {{ item.orgName }}</b>
                    </div>
                  </div>
                  <div class="ant-space-item" v-if="item.recordList">
                    <p class="name">转办、委派记录
                      <el-tag v-if="item.taskState === 0"
                              v-for="e in taskTypeFilter(item.taskType)"
                              :key="e.label"
                              :type="e.type"
                              effect="dark"
                      >
                        {{ e.label }}
                      </el-tag>
                    </p>
                    <div v-for="(record,index) in item.recordList" :key="index">{{ record }}</div>
                  </div>
                  <div class="ant-space-item">
                    <el-tag
                        v-for="e in stateList(item.taskState)"
                        :key="e.label"
                        :type="e.type"
                        effect="dark"
                    >
                      {{ e.label }}
                    </el-tag>
                    <el-tag v-if="item.taskLabel === 0"
                            effect="dark" type="danger"
                    >
                      驳回
                    </el-tag>
                  </div>

                  <div class="ant-space-item" v-if="item.taskType === 0">
                    发起时间：{{ item.createTime }}
                  </div>
                  <div class="ant-space-item" v-else>
                    创建时间：{{ item.createTime }}
                  </div>
                  <div class="ant-space-item" v-if="item.finishTime">
                    完成时间：{{ item.finishTime }}
                  </div>
                  <div v-if="[1,10,12].indexOf(item.taskType) > -1 && [2,3].indexOf(item.taskState) > -1">
                    <div class="ant-space-item" style="padding-bottom: 5px;">审批意见:</div>
                    <div class="ant-space-item">
                    <span class="ant-space-item">
                      <span class="approval-remark" v-if="item.authYesRemarks"
                      >{{ item.authYesRemarks }}</span
                      >
                      <span class="approval-remark" v-if="item.authNoRemarks"
                      >{{ item.authNoRemarks }}</span
                      >
                    </span>
                    </div>
                  </div>
                  <div v-if="item.copyPersonTitle" style="margin-top: -20px;">
                    <div class="ant-space-item" style="padding-bottom: 5px;">抄送人:</div>
                    <div class="ant-space-item">
                      <span>{{ item.copyPersonTitle }}</span>
                    </div>
                  </div>
                  <div v-if="item.taskLabel === 0">
                    <div class="ant-space-item" style="padding-bottom: 5px;">驳回原因:</div>
                    <div class="ant-space-item">
                    <span class="ant-space-item">
                      <span class="approval-remark" v-if="item.rejectReason"
                      >{{ item.rejectReason }}</span
                      >
                    </span>
                    </div>
                  </div>
                </div>
              </template>
            </el-step>
          </el-steps>
        </div>
      </zh-col>
    </zh-row>
  </div>
</template>

<script lang="ts" setup name="flowDeatilForm">
import authRemarks from "./small/authRemarks.vue";
import type { ComponentPublicInstance } from 'vue'

import {
  defineAsyncComponent,
  ref,
  reactive,
  inject,
  onMounted,
  nextTick,
  computed,
  watch,
  shallowRef
} from "vue";

const props = defineProps({
  instanceId: {
    type: String,
    required: true,
  },
  businessKey: {
    type: String,
    required: true,
  },
  instanceState: {
    type: Number,
    required: true,
  },
  processType: {
    type: Number,
    required: true,
  },
})

const emits = defineEmits(["update:taskId", "update:taskState","update:eventType"]);
const hisNodeList = computed(() => {
  //排除第一个（发起节点）和最后一个节点
  let arr = processData.processStepInfoList.slice(0,-1).slice(1);
  return arr.filter(function (item) {
    return item.taskState === 2;
  });
});

const getCompleteProcessStepInfoList = computed(()=> {
  return processData.processStepInfoList.filter(item => item.taskState !== 0)
})

const getAuditProcessStepInfoList = computed(()=> {
  const list = processData.processStepInfoList.filter(item => item.taskState === 0);
  if(!list || list.length === 0){
    return null;
  }
  const result = {}
  result.displayName = list[0].displayName
  result.list = list;
  return result;
});

const authRemarksComponent = ref<ComponentPublicInstance | null>(null);
const currentComponent = ref();
const componentList = ref([]);
const hasOperationData = ref([]);
const otherConfig = ref({});
const configFromCus = ref({});
const items = ref<Array<Item>>([
  {type: "primary", label: "跳转", taskState: 1},
  {type: "success", label: "已同意", taskState: 2},
  {type: "info", label: "已撤销", taskState: 4},
  {type: "warning", label: "正在活动", taskState: 0},
  {type: "danger", label: "已拒绝", taskState: 3},
]);
const taskTypeList = ref<Array<Item>>([
  {type: "primary", label: "转办中", taskType: 10},
  {type: "warning", label: "委派中", taskType: 11},
  {type: "primary", label: "委派->转办中", taskType: 13},
  {type: "success", label: "委派已归还任务", taskType: 12},
]);
const stateList = (state) => {
  return items.value.filter((item) => item.taskState == state);
};
const taskTypeFilter = (taskType) => {
  return taskTypeList.value.filter((item) => item.taskType == taskType);
};


const performTypeList = ref<Array<Item>>([
  {value: 1, label: "顺签"},
  {value: 2, label: "会签"},
  {value: 3, label: "或签"},
]);
const getPerformType = (performType) => {
  return performTypeList.value.filter((item) => item.value == performType);
};
const processData = reactive({
  processStepInfoList: [],
  currentNode: {},
});

const updateEventType = (eventType) => {
  emits('update:eventType', eventType);
}

// 创建一个ref，用于存储子组件的实例
const childComponents = ref({});
const operationFlag = ref(false);
const changeOperationFlag = inject('changeOperationFlag');
const handleOperationFlag = (opeationInfo)=>{
  operationFlag.value = opeationInfo.operationFlag;
  if (changeOperationFlag) {
    changeOperationFlag(opeationInfo);
  }
}


// 设置ref的函数，它将基于组件的名字来设置ref的键值
function setChildRef(componentName) {
  return (el) => {
    if (el) {
      childComponents.value[componentName] = el;
    }
  };
}

async function loadComponent(currentNode) {
  // // 使用动态导入来异步加载组件 import(`./${local}.vue`) vite 不支持 ${}写法
  // const { default: component } = await import(`@/views/system/auditRE/test/test.vue`);
  // console.log(component);
  // // 设置当前组件为异步加载的组件
  // currentComponent.value = component;
  componentList.value = [];
  let modules = import.meta.glob("@/views/system/auditRE/*/*.vue"); //取auditRE下的一级目录里面的vue文件
  const {default: component} = await import(`@/views/system/auditRE/404/index.vue`);
  currentComponent.value = shallowRef(component)
  if (currentNode.formMode == 1) {
    // 使用await 确保同步
    for (const path in modules) {
      const mod = await modules[path]();
      if (path === currentNode.formUrl.replace(/\\/g, "/")) {
        currentComponent.value = shallowRef(mod.default);
      }
      // modules[path]().then((mod) => {
      //   console.log(currentNode.formUrl.replace(/\\/g, "/"))
      //   if (path === currentNode.formUrl.replace(/\\/g, "/")) {
      //     currentComponent.value = mod.default;
      //   }
      // });
    }
    componentList.value.push({
      mod: currentComponent.value,
      taskId: currentNode.taskId,
      index: 0,
    });
  } else {
    const pathList = [];
    const taskIdList = [];
    processData.processStepInfoList.forEach((item) => {
      pathList.push(item.formUrl.replace(/\\/g, "/"));
      taskIdList.push(item.taskId);
    });
    for (const path in modules) {
      const mod = await modules[path]();
      let index = pathList.indexOf(path);
      if (index > -1) {
        componentList.value.push({
          //不能将响应式组件转换为响应式对象,因此用shallowRef 包裹
          mod: shallowRef(mod.default),
          taskId: taskIdList[index],
          index: index,
        });
      }
      // modules[path]().then((mod) => {
      //   let index = pathList.indexOf(path);
      //   if (index > -1) {
      //     componentList.value.push({
      //       mod: mod.default,
      //       taskId: taskIdList[index],
      //       index: index,
      //     });
      //   }
      // });
    }
    //排序 节点小到大
    if (componentList.value.length > 0) {
      componentList.value.sort((a, b) => a.index - b.index);
    }
  }
}

onMounted(() => {
  $api.common.send
      .post("flowLongQuery009", {flwInstanceId: props.instanceId})
      .then((res) => {
        processData.processStepInfoList = res.result;
        const processStep =
            processData.processStepInfoList[processData.processStepInfoList.length - 1];
        processData.currentNode.taskId = processStep.taskId;
        processData.currentNode.formUrl = processStep.formUrl;
        processData.currentNode.formMode = processStep.formMode;
        loadComponent(processData.currentNode);
        emits('update:taskId', processData.currentNode.taskId);
        const operationInfo = {}
        if(processStep && processStep.operationFlag){
          operationInfo.operationFlag= true
          operationInfo.hasOperationData= processStep.hasOperationData
          if(processStep.hasOperationData){
            hasOperationData.value = processStep.hasOperationData
          }
          otherConfig.value = {
            actorWay: processStep.actorWay,
            actorWayType: processStep.actorWayType,
            orgScope: processStep.orgScope,
            roleScope: processStep.roleScope,
            taskActorConfigForNextStep: processStep.taskActorConfigForNextStep,
          }
        }else {
          operationInfo.operationFlag= false
        }
        handleOperationFlag(operationInfo)

      })
      .catch(() => {
      });
});

//获取还原页面上的下一节点的审核人员
const getActorListForFunction = (data) => {
  if(otherConfig.value.actorWayType === 5){
    configFromCus.value = data;
  }
}

//获取组件数据
const getData = () => {
  const resultData = {sys: {}}
  for (let key in childComponents.value) {
    Object.assign(resultData, childComponents.value[key].getData())
  }
  Object.assign(resultData.sys, authRemarksComponent.value.getData())
  return resultData;
}

defineExpose({
  getData
})
</script>

<style lang="scss" scoped>
.ant-space-item {
  box-sizing: border-box;
  display: block;
  font-size: 13px;
  color: rgba(0, 0, 0, 0.43);
  position: relative;
  margin: 0;
  padding-bottom: 20px;
  list-style: none;

  .name {
    color: black;
    font-weight: bold;
  }

  .approval-remark {
    background-color: #fff;
    background-image: none;
    border-radius: 5px;
    border-width: 2px;
    border-color: #dcdfe6;
    border-style: dotted;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    display: inline-block;
    font-size: inherit;
    line-height: 30px;
    outline: none;
    -webkit-transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
    transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
    padding: 0 9px;
    height: auto;
    width: 100%;
  }
}
</style>
